﻿@page "/login"
@rendermode InteractiveAuto
@inject IJSRuntime jsr
@inject NavigationManager nav

<h3>Login</h3>

<p>@message</p>

<EditForm Model="user" OnValidSubmit="OnValid" style="max-width:500px;">
	<DataAnnotationsValidator />
	<ValidationSummary />
	<div class="mb-2">
		<InputText class="form-control" @bind-Value="user.email" placeholder="Enter Email"></InputText>
	</div>
	<div class="mb-2">
		<InputText type="password" class="form-control" @bind-Value="user.password" placeholder="Enter Password"></InputText>
	</div>
	<div class="mb-2 text-right">
		<button class="btn btn-secondary" disabled="@isDisabled">login</button>
	</div>
</EditForm>

@code {

	LoginModel user = new LoginModel();
	string message = string.Empty;
	bool isDisabled = false;

	private async Task OnValid()
	{
		using (HttpClient Http = new HttpClient { BaseAddress = new Uri(nav.BaseUri) })
		{

			isDisabled = true;
			using (var msg = await Http.PostAsJsonAsync<LoginModel>("/api/auth/login", user, System.Threading.CancellationToken.None))
			{
				if (msg.IsSuccessStatusCode)
				{
					LoginResult result = await msg.Content.ReadFromJsonAsync<LoginResult>();
					message = result.message;
					isDisabled = false;
					if (result.success)
						await jsr.InvokeVoidAsync("localStorage.setItem", "user", $"{result.email};{result.jwtBearer}").ConfigureAwait(false);
				}
			}
		}
	}
}